package com.code.test.first.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 层序遍历
 * https://juejin.cn/post/7108566681022103589
 */
public class Code102 {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(10, null, null);
        TreeNode right20 = new TreeNode(20, null, null);
        TreeNode left30 = new TreeNode(30, null, null);
        TreeNode right40 = new TreeNode(40, null, null);
        TreeNode left3 = new TreeNode(3, left10, right20);
        TreeNode right5 = new TreeNode(5, left30, right40);
        TreeNode root = new TreeNode(1, left3, right5);

        List<List<Integer>> ret = level2(root);
        System.out.println(ret);
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        level(root, 0, ret);

        return ret;
    }

    private static void level(TreeNode node, Integer deep, List<List<Integer>> resList) {
        if (node == null) return;
        deep++;
        if (resList.size() < deep) {
            resList.add(new ArrayList<>());
        }

        resList.get(deep - 1).add(node.val);
        level(node.left, deep, resList);
        level(node.right, deep, resList);
    }

    public static List<List<Integer>> level2(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> ret = new ArrayList<>();

        queue.add(root);
        while (!queue.isEmpty()) {

            //这里是每一层的大小，直接圈定好，循环里面再加是为了下一次做准备
            /**
             * queue是上次保存下来的上一级，然后这次遍历时，把每个节点的值入库，然后把每个节点的左右子节点入queue，给下次用
             */
            int len = queue.size();
            List<Integer> cur = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) queue.add(node.right);
            }
            ret.add(cur);
        }
        return ret;
    }
}
